package com.gzist.blog_system.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzist.blog_system.domain.Permission;
import com.gzist.blog_system.domain.User;
import com.gzist.blog_system.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class SysUserDetailsService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //先进行自定义登录数据源
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        log.info("user即用户数据====>{}",user);
        if (user == null) {
            //当查询结果为空说明账号错误，手动抛出业务一场
            log.info("=====》查询结果为空说明账号错误，手动抛出业务一场");
            throw new UsernameNotFoundException("账号错误！！！");
        }
        //将其下所拥有得权限查询出来并存进去
        List<String> perms = user.getPerms();
        List<Permission> permissions = userMapper.getPermissions(user.getId());
        for (Permission permission : permissions) {
            String str = permission.getPerms();
            //在这里做判断是为了让权限标识集合不存在空字符串，防止权限获取的时候出错
            if (StringUtils.hasLength(str)) {
                perms.add(str);
            }
        }
        //加予身份
        user.setAdmin();
        log.info("user即用户数据22====>{}",user);
        return user;
    }
}
